package com.beiming.kotlindemo.activity

import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.beiming.kotlindemo.Msg
import com.beiming.kotlindemo.R
import com.beiming.kotlindemo.adapter.MsgAdapter
import kotlinx.android.synthetic.main.activity_ui_best_practice.*

class UIBestPracticeActivity : BaseActivity(), View.OnClickListener {

    override fun getContentResId() = R.layout.activity_ui_best_practice

    private val msgList = ArrayList<Msg>()

    //private var adapter: MsgAdapter? = null
    //lateinit 延迟初始化
    private lateinit var adapter: MsgAdapter

    override fun initView() {
        initMsg()
        val layoutManager = LinearLayoutManager(this)
        recyclerview.layoutManager = layoutManager
        //判断变量是否初始化，避免重复初始化,  ::adapter.isInitialized可判断变量adapter是否已初始化
        if (!::adapter.isInitialized) {
            adapter = MsgAdapter(msgList)
        }
        recyclerview.adapter = adapter
        btn_send.setOnClickListener(this)
    }

    override fun initData() {

    }

    private fun initMsg() {
        val msg1 = Msg("Hello guy.", Msg.TYPE_RECEIVED)
        msgList.add(msg1)
        val msg2 = Msg("Hello. Who is that ?", Msg.TYPE_SENT)
        msgList.add(msg2)
        val msg3 = Msg("This is Tom. Nice to meet you.", Msg.TYPE_RECEIVED)
        msgList.add(msg3)
    }

    override fun onClick(v: View?) {
        when (v) {
            btn_send -> {
                val content = et_msg.text.toString()
                if (content.isNotEmpty()) {
                    val msg = Msg(content, Msg.TYPE_SENT)
                    msgList.add(msg)
                    adapter.notifyItemInserted(msgList.size - 1)
                    recyclerview.scrollToPosition(msgList.size - 1)
                    et_msg.setText("")
                }
            }
        }
    }
}